package com.jiangjun.fetch.common;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiangjun.fetch.servlet.Start;
import com.jiangjun.fetch.util.UrlUtil;

/**
 * 标签过滤，收集Image标签
 * 
 * @author Administrator
 * 
 */
public class ElementParse {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 过滤标签
	 */
	public void tagParse(Element element, WebContext ctx) throws Exception {

		removeTag(element);
		List<Node> childList = element.content();
		for (int i = 0; i < childList.size(); i++) {
			// element的孩子节点
			Node child = childList.get(i);
			if (child.getNodeType() == Node.ELEMENT_NODE) {
				Element eleChild = (Element) child;
				// 刪除標籤里的style樣式
				if (eleChild.attribute("style") != null) {
					String style = eleChild.attributeValue("style")
							.toLowerCase();
					// 如果style里面有display: none的属性，则删除该标签
					if (style.indexOf("display: none") > -1
							|| style.indexOf("display:none") > -1) {
						element.remove(eleChild.detach());
					} else {
						eleChild.remove(eleChild.attribute("style"));
						// 保留缩进样式
						// 针对有0em的情况作进一步优化
						if (style.indexOf("text-indent") > -1
								&& style.indexOf("2em") > -1) {
							eleChild.addAttribute("style", "text-indent:2em");
						}
					}
				}
				removeAttribute(eleChild);
				// 从正文中获取摘要
				String tagName = eleChild.getName();
//				if (tagName.equalsIgnoreCase("p")
//						|| tagName.equalsIgnoreCase("div")
//						|| tagName.equalsIgnoreCase("span")) {
//					String text = eleChild.getTextTrim().trim();
//					text = text.replaceAll("\n", "");
//					text = text.replaceAll("\t", "");
//					text = text.replaceAll("　　", "");
//					text = text.replaceAll("<br>", "");
//					text = text.replaceAll("\\|", "");
//					text = text.replaceAll(" ", "");// 替换全角空格
//					text = text.replaceAll("	　　", "");
//					if (tagName.equalsIgnoreCase("p")) {
//						// 统一给p添加缩进
//						if (eleChild.attribute("style") != null
//								&& eleChild.attributeValue("style").indexOf(
//										"text-indent:2em") > -1) {
//							// 已经有了缩进
//						} else {
//							String item_text = eleChild.getText();
//							if (!item_text.startsWith("　　")
//									&& !item_text.startsWith("　　")
//									&& !item_text.startsWith("	　　")) {
//								eleChild.addAttribute("style",
//										"text-indent:2em");
//							}
//						}
//					}
//				}
				if (tagName.toLowerCase().matches(
						"style|script|iframe|select|embed|em|object")) {
					// 需要删除的标签
					element.remove(eleChild.detach());
				} else if (tagName.matches("p|strong")) {
					if (eleChild.getText().matches("来源"))
						element.remove(eleChild.detach());
				} else if ("img".equalsIgnoreCase(tagName)) {
					// 删除过小的图片或者本身打不开的
					// 注意修改处，在处理涂牛的时候搜集的是file属性里的图片链接
					// if (!doImage(eleChild, ctx)) {
					// element.remove(eleChild.detach());
					// }
					// 收集图片
					if (true) {
						ImageFetch is = new ImageFetch();
						is.setId(ctx.getImgCount());
						is.setNews_id(ctx.getId());
						is.setImg_id(ConstantVariable.SURF_IMG_ID
								+ ctx.getImgCount());
						String src = eleChild.attributeValue("src");
						if (!src.toLowerCase().startsWith("http")) {
							// 补全
							try {
								URL url = new URL(ctx.getUrl());
								// 解决以下问题
								// http://www.adquan.com/article1.php?id=14028
								// ../../upload2/2012_09_07_1347011571_22867.jpg
								if (src.indexOf(url.getHost()) == -1
										&& src.startsWith("..")
										&& ctx.getUrl().indexOf("adquan") > -1) {
									src = src
											.substring(src.lastIndexOf("../") + 3);
								}
								src = UrlUtil.guessURL(url, src).toString();
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
						if (eleChild.attribute("id") != null) {
							eleChild.attribute("id").detach();
						}
						eleChild.addAttribute("id", is.getImg_id());
						
						if(ctx.getType().equals("3"))
						{
							src = src.replace("-lp", "");
						}
						is.setImg_src(src);
						ctx.getImgList().add(is);
						ctx.setImgCount(ctx.getImgCount() + 1);
					}
				}else if("a".equalsIgnoreCase(tagName)){
					//收集A标签
					
				}
				if (eleChild.getTextTrim().matches("(?i)[下上]\\s*一*\\s*[页章节张]")
						|| eleChild.getTextTrim().matches(
								"(【|\\[|\\()\\d+(】|\\]|\\))")
						|| eleChild.getTextTrim().matches("\\d+")) {
					element.remove(eleChild.detach());
				}
				tagParse(eleChild, ctx);
			}
		}
	}

	public void removeAttribute(Element element) {
		ArrayList<String> removeAttributes = Start.removeAttributes;
		for (String attribute : removeAttributes) {
			Attribute attr = element.attribute(attribute);
			if (attr != null) {
				element.remove(attr);
			}
		}
	}

	public void removeTag(Element element) {
		ArrayList<String> removeElementTags = Start.removeElementTags;
		for (String tags : removeElementTags) {
			List<Element> items = element.selectNodes("//" + tags);
			for (Element ele : items) {
				element.remove(ele.detach());
			}
		}
	}
}
